﻿
if (!wkh) {
    var wkh = {
        version: "mobile:1.01"
    };
}

wkh.tools = function (str) {
    return Array.prototype.clone.call(document.querySelectorAll(str));
};

(function () {
    var $;
    if (window.$ != null && window.$ !== wkh.tools) {//
        console.log("$全局变量冲突,可使用fullName方法使用全名并回复原变量");

        $ = window.$;
    }

    window.$ = wkh.tools;
    wkh.select = wkh.tools;


    wkh.tools.fullName = function () {
        if ($ != null) {
            window.$ = $;
        } else {
            try {
                delete window.$;
            } catch (e) {
                window.$ = undefined;
            }
        }
    };
}());

//任何传递给load的参数为函数，在文档准备就绪时调用，若文档已经就绪，马上调用
//this绑定到document
wkh.tools.ready = (function () {
   var funcs = [];//运行的函数列队
    var ready = false;//is the document ready

    var funcsAllDown = [];//所有资源加载完毕后执行
    var readyAllDown = false;//是否加载完毕

    //the event handler invoked when the document becomes ready
    function doFuncs(e,type){
        //if we've already run once, just return
        if (type && readyAllDown) {
            return;
        }
        if (!type && ready) {
            return;
        }

        //if this was a readystatechange event where the state changed to 
        //something other than "complete", then we're not ready yet
        if (e.type === "readystatechange" && document.readyState !== "complete") return;

        //set the ready flag to true
        var f;
        if (type) {
            readyAllDown = true;
            f = funcsAllDown;
        } else {
            ready = true;
            f = funcs;
        }
        

        //run all registered functions.
        for (var i = 0, l = f.length; i < l; ++i) {
            f[i].call(document);
        }

        //set the function array to null
        if (type) {
            funcsAllDown = [];
        } else {
            funcs = [];
        }
    }

    function handler(e) {
        doFuncs(e);
    }
    function handlerAllDown(e) {
        doFuncs(e, true);
    }

    //register the handler for any event we might receive
    document.addEventListener("DOMContentLoaded", handler, false);
    document.addEventListener("readystatechange", handler, false);
    window.addEventListener("load", handler, false);

    window.addEventListener("load", handlerAllDown, false);

    //return the ready function
    return function (f,isAllDown) {
        if (isAllDown) {
            if (readyAllDown) f.call(document);
            else funcsAllDown.push(f);
        } else {
            if (ready) f.call(document);//if already ready, just run it
            else funcs.push(f);//otherwise,queue it for later
        }
    };
}());

wkh.tools.loadScript = function (url, node, fn) {//异步加载和执行脚本
    if (Object.classof(node) === "Function") {
        fn = node;
        node = null;
    } 

    node = node || (document.head || document.getElementsByTagName("head")[0]);

    var s = document.createElement("script");

    if (fn) {
        s.addEventListener("load", fn);
    }

    s.src = url;
    node.appendChild(s);
};

wkh.tools.loadCSS = function (url) {
    if (document.createStyleSheet) {
        document.createStyleSheet(url);
    } else {
        var node = document.head || document.getElementsByTagName("head")[0];
        var l = document.createElement("link");
        node.appendChild(l);
        l.setAttribute("rel", "stylesheet");
        l.setAttribute("type", "text/css");
        l.setAttribute("href", url);
    }
};

wkh.tools.addStyle = function (styles) {
    var styleElt, styleSheet;
    if (document.createStyleSheet) {
        styleSheet = document.createStyleSheet();
    } else {
        var node = document.head || document.getElementsByTagName("head")[0];
        styleElt = document.createElement("style");
        node.appendChild(styleElt);
        styleSheet = document.styleSheets[document.styleSheets.length - 1];
    }

    if (Object.prototype.toString.call(styles).slice(8, -1) === "String") {
        if (styleElt) styleElt.innerHTML = styles;
        else styleSheet.cssText = styles;
    } else {
        var i = 0, selector;
        for (selector in styles) {
            if (styleSheet.insertRule) {
                var rule = selector + "{" + styles[selector] + "}";
                styleSheet.insertRule(rule, i++);
            } else {
                styleSheet.addRule(selector, styles[selector], i++);
            }
        }
    }
};

wkh.tools.switchStylesheet = function (ss, method) {//控制样式表的开关
    if (ss==undefined) {
        return;
    }

    if (Object.prototype.toString.call(ss).slice(8, -1) === "Number") {
        switch (method) {
            case "close":
                document.styleSheets[ss].disabled = true;
                break;
            case "open":
                document.styleSheets[ss].disabled = false;
                break;
            default:
                document.styleSheets[ss].disabled = !document.styleSheets[ss].disabled;
                break;
        }
    } else {
        for (var i = 0; i < document.styleSheets.length; ++i) {
            if (document.styleSheets[i] === ss) {
                switch (method) {
                    case "close":
                        ss.disabled = true;
                        break;
                    case "open":
                        ss.disabled = false;
                        break;
                    default:
                        ss.disabled = !ss.disabled;
                        break;
                }

                break;
            }
        }
    }
};//控制样式表的开关

wkh.tools.memorize = function (f, thisObj) {//接收一个函数作为参数，返回带记忆能力的函数，牺牲空间复杂度换取更优的时间复杂度
    var cache = {};//将值保存
    thisObj = thisObj || window;

    return function () {
        var key = arguments.length + Array.prototype.join.call(arguments, ",");//将参数转化为缓存键值
        if (key in cache) return cache[key];
        else return cache[key] = f.apply(thisObj, arguments);
    };
};

wkh.tools.preFixCss = wkh.tools.memorize(function (cssRules) {//如果有，返回带前缀的css名(具有记忆功能)
    if (!cssRules) {
        return cssRules;
    }

    var matched = null;
    if ((matched = /^(-?webkit|-?ms|-?moz|-?o)?(-?)([a-zA-Z0-9]*)/.exec(cssRules)) && cssRules in document.body.style) {
        return cssRules;
    }

    if (matched) {
        var cssRules = matched[3];
        cssRules = cssRules.slice(0, 1).toLowerCase() + cssRules.slice(1);
        if (cssRules in document.body.style) {
            return cssRules;
        }
        if (matched[2] === "-") {
            var temArr = cssRules.split("-");
            for (var i = 1; i < length; ++i) {
                temArr[i] = temArr[i].slice(0, 1).toUpperCase() + temArr[i].slice(1);
            }
            cssRules = temArr.join("");
        }
        
    }

    if (cssRules.length === 1) {//首字母转为大写，保存副本
        var CssRules = cssRules.toUpperCase();
    } else {
        var CssRules = cssRules.slice(0, 1).toUpperCase() + cssRules.slice(1);
    }

    if ("ms" + CssRules in document.body.style) {
        return "ms" + CssRules;
    } else if ("webkit" + CssRules in document.body.style) {
        return "webkit" + CssRules;
    } else if ("moz" + CssRules in document.body.style) {
        return "moz" + CssRules;
    } else if ("o" + CssRules in document.body.style) {
        return "o" + CssRules;
    } else {
        return null;
    }
}, wkh.tools);

wkh.tools.getSameAncestralNode = function (/*...*/) {//找到元素共同祖先元素(如果可能，可包括自身元素)//效率有待调整
    if (arguments.length === 0) {
        throw new Error("没有参数");
    }

    var isArgumentsSame = true;//所有参数是否相同
    for (var i in arguments) {
        if (arguments[i] !== arguments[0]) {
            isArgumentsSame = false;
            break;
        }
    }

    if (isArgumentsSame) {//若相同，反回参数
        return arguments[0];
    }

    var nodeList = [];//每个参数元素的祖先元素列表
    for (var i in arguments) {
        var nowNode = arguments[i];
        var thisNodeList = [];//当前参数祖先元素列表;
        do {
            thisNodeList.unshift(nowNode);
        } while (nowNode = (nowNode.parentNode || nowNode.parentElement));

        nodeList.push(thisNodeList);
    }

    //去除相同的元素
    var sameNode = null;

    while (true) {
        var isSame = true;
        for (var i in nodeList) {
            if (nodeList[i][0] !== nodeList[0][0]) {//如果不相同，跳出
                isSame = false;
                break;
            }
        }

        if (isSame) {//如果相同
            sameNode = nodeList[i][0];
            for (var i in nodeList) {//推出相同元素
                nodeList[i].shift();
            }
        } else {//否则跳出循环
            break;
        }
    }

    return sameNode;
};

wkh.tools.getUrlArgs = function () {//解析url查询参数
    var args = {};
    var query = location.search.substring(1);//去除查询串中的"?"
    var pairs = query.split("&");
    var length = pairs.length;
    for (var i = 0; i < length; ++i) {
        var pos = pairs[i].indexOf('=');
        if (pos === -1) continue;//如果不存在'='号，跳过
        var name = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        value = decodeURIComponent(value);//对value进行解码
        args[name] = value;
    }

    args.length = pairs.length;
    return args;
};

wkh.tools.getRandomNum = function (min, max, isInt) {//产生随机数函数
    min = min || 0;
    max = max || 10;
    isInt = isInt === false ? false : true;

    var range = max - min;
    var rand = Math.random();

    if (isInt) {
        return (min + Math.round(rand * range));
    } else {
        return (min + rand * range);
    }
};

wkh.tools.getRandomNumList = function (length, min, max, isInt) {//产生不重复的随机数列表
    var numArr = [];

    var random;
    while(numArr.length<length) {
        random = wkh.tools.getRandomNum(min, max, isInt);
        if (numArr.contains(random) === -1) {
            numArr.push(random);
        }
    }
    return numArr;
};

wkh.tools.getInputSelection = function (inputDom) {//获得input对象选中文本
    var tagName = inputDom.tagName.toUpperCase();
    if (tagName !== "INPUT" && tagName !== "TEXTAREA") {
        throw new Error("对象不是文本输入框");
    }
    if ("selectionStart" in inputDom) {
        if (document.activeElement === inputDom) {
            return inputDom.value.substring(inputDom.selectionStart, inputDom.selectionEnd);
        } else {
            return "";
        }
    } else {
        var range = document.selection.createRange();
        if (range.parentElement() === inputDom) {
            return range.text;
        } else {
            return "";
        }
    }
};

wkh.tools.setInputSelection = function (inputDom, startIndex, endIndex) {//设置input地象选中文本
    var tagName = inputDom.tagName.toUpperCase();
    if (tagName !== "INPUT" && tagName !== "TEXTAREA") {
        throw "对象不是文本输入框";
    }
    if (inputDom.setSelectionRange) {
        inputDom.setSelectionRange(startIndex, endIndex);
    }
    else if (inputDom.createTextRange) //IE 
    {
        var range = inputDom.createTextRange();
        range.collapse(true);
        range.moveStart('character', startIndex);
        range.moveEnd('character', endIndex - startIndex);
        range.select();
    }
    inputDom.focus();
};

wkh.tools.loop = function (fn, time) {//定时循环
    if (!time) {
        time = 300;
    }

    function loopfn() {
        if (fn() === false) {
            setTimeout(loopfn, time);
        }
    }

    setTimeout(loopfn, time);
};

wkh.tools.setInnerKey = function (obj,key, val) {//如果可以，设置对象内置方法或值，不可枚举和配置
    try {
        Object.defineProperty(obj, key, {
            writable: true,
            enumerable: false,
            configurable: false,
            value: val
        });
    } catch (e) {
        obj[key] = val;
    }
};

wkh.tools.realBoxSize = function (dom) {
    var body = document.body || document.getElementsByTagName("body")[0];
    var div = document.createElement("div");
    div.css({
        position: "absolute",
        visibility: "hidden",
        padding: 0,
        margin: 0,
        border: "none"
    });
    body.appendChild(div);

    var cloneNode = dom.cloneNode(true);
    div.appendChild(cloneNode);
    var returnBox = { width: cloneNode.css("width"), height: cloneNode.css("height") };

    div.removeNode(true);
    return returnBox;
};

(function () {//动画事件检测
    var pre = ["webkit", "o", "moz"];
    var transitionNames = {
        "webkit": "webkitTransitionEnd",
        "o": "oTransitionEnd"
    };
    var animationNames = {
        "webkit": ["webkitAnimationStart", "webkitAnimationEnd", "webkitAnimationIteration"],
        "o": ["oAnimationStart", "oAnimationEnd", "oAnimationIteration"]
    };

    var thisPre = "", thisTransitionName = "transitionend", thisAnimationName = ["animationstart", "animationend", "animationiteration"];
    var testDivStyle = document.createElement("div").style;

    if ("transition" in testDivStyle && "animation" in testDivStyle) {
    } else {
        for (var i = 0, l = pre.length; i < l; ++i) {
            thisPre = pre[i];
            if ((thisPre + "Transition") in testDivStyle || (thisPre + "Animation") in testDivStyle) {
                break;
            }
            thisPre = false;
        }
        if (thisPre !== false) {
            if (thisPre !== "moz") {
                if (!("transition" in testDivStyle)) {
                    thisTransitionName = transitionNames[thisPre];
                }
                if (!("animation" in testDivStyle)) {
                    thisAnimationName = animationNames[thisPre];
                }
            }
        } else {
            thisTransitionName = "";
            thisAnimationName = ["", "", ""];
        }
    }

    wkh.tools.event = {};
    wkh.tools.event.transitionend = thisTransitionName;
    wkh.tools.event.animationstart = thisAnimationName[0];
    wkh.tools.event.animationend = thisAnimationName[1];
    wkh.tools.event.animationiteration = thisAnimationName[2];
}());